/*
 * RecycleBinHandler.java
 *
 * Created on April 7, 2007, 9:54 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package edu.byu.isys413.group1E.handlers;

import edu.byu.isys413.group1E.data.*;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * This class Handles processing and interaction needed to read and write objects to and from
 * the RecycleBin table.
 * @author tkulbeth
 */
public class RecycleBinHandler {
    
    private static RecycleBinHandler instance = null;
    
    /** Creates a new instance of RecycleBinHandler */
    public RecycleBinHandler() {
    }
    
    /**
     *gets you an instance of RecycleBinHandler
     *
     * @return instance of RecycleBinHandler
     */
    public static synchronized RecycleBinHandler getInstance() {
        if (instance == null) {
            instance = new RecycleBinHandler();
        }
        return instance;
    }
    
    /**
     * Creates a new instance of RecycleBinHandler
     * using data from a BackupDataBO and adding a field for the date added.
     * 
     * @param bkData contains the BackupDataBO to be "copied"
     * @return a RecycleBinBO with the given BackupDataBO information.
     */
    public RecycleBinBO extractBackupInfo(BackupDataBO bkData){
        RecycleBinBO rb = new RecycleBinBO(bkData.getId());
        //get today's date
        Calendar cal = Calendar.getInstance();
        Date today = cal.getTime();
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        String todayDate = fmt.format(today);
        rb.setDateTrashed(todayDate);
        rb.setDateUploaded(bkData.getDateUploaded());
        rb.setExt(bkData.getExt());
        rb.setFileName(bkData.getFileName());
        rb.setFileSize(bkData.getFileSize());
        rb.setMembershipID(bkData.getMembershipID());
        rb.setStatus(bkData.getStatus());
        rb.setIsDirty(true);
        rb.setAlreadyInDB(false);
        
        return rb;
    }
    
    /**
     * Saves a given file to the database.
     * 
     * @param rs contains the result set containing the file to be saved.
     * @param bkData contains the BackupDataBO containing the data to be
     *transferred from the BackupData table to the RecycleBin.
     * @return the guid for the BackupData record
     */
    public String saveFileToRecycleBin(ResultSet rs, BackupDataBO bkData){
        String guid = null;
        try {
            RecycleBinBO rb = this.extractBackupInfo(bkData);
            
            //save the metaData to the dB
            Connection conn = ConnectionPool.getInstance().get();
            RecycleBinDAO.getInstance().save(rb, conn);
            
            //read the file from the result set
            byte[] b = null;
            while(rs.next()){
                b = rs.getBytes("fileObject");
            }
            ByteArrayInputStream stream = new ByteArrayInputStream(b);
            
            //save the file to the new line in the database
            PreparedStatement pstmt = conn.prepareStatement("UPDATE RecycleBin SET fileObject = ? WHERE BackupID = ?");
            pstmt.setBinaryStream(1, (InputStream)stream, b.length);
            pstmt.setString(2, bkData.getId());
            pstmt.executeUpdate();
            conn.commit();
            
            ConnectionPool.getInstance().release(conn);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return guid;
    }
    
    /**
     * Reads the actual file out of the database according to the guid provided.
     * @param id contains the id of the file to be read
     * @return a result set containing the file and accompanying information.
     */
    public ResultSet readFileByGUID(String id){
        ResultSet rs = null;
        try {
            Connection conn = ConnectionPool.getInstance().get();
            PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM RecycleBin WHERE BackupID = ?");
            pstmt.setString(1, id);
            rs = pstmt.executeQuery();
            
            ConnectionPool.getInstance().release(conn);
        } catch (SQLException ex) {
            ex.printStackTrace();
        } catch (ConnectionPoolException ex) {
            ex.printStackTrace();
        }
        return rs;
    }
}
